package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

type JobCtlController struct {
	beego.Controller
}

type JobCtlListReq struct {
	JobId     string   `form:"jobId"`
	ExecDay   []string `form:"execDay"`
	ExecTimes []string `form:"execTimes"`
	Valid     []string `form:"valid"`
	Draw      int64    `form:"draw"`
	Start     int      `form:"start"`
	Length    int      `form:"length"`
}

type JobCtlListRsp struct {
	Draw            int64        `json:"draw"`
	RecordsTotal    int64        `json:"recordsTotal"`
	RecordsFiltered int64        `json:"recordsFiltered"`
	Data            []*TblJobCtl `json:"data"`
	Error           string       `json:"error"`
}

func (c *JobCtlController) Get() {
	var (
		err error
		req = new(JobCtlListReq)
		rsp = new(JobCtlListRsp)
	)

	_ = c.ParseForm(req)
	_ = c.Ctx.Input.Bind(&req.ExecDay, "execDay")
	_ = c.Ctx.Input.Bind(&req.ExecTimes, "execTimes")
	_ = c.Ctx.Input.Bind(&req.Valid, "valid")

	o := orm.NewOrm()

	rsp.RecordsTotal, err = o.QueryTable("tbl_job_ctl").Filter("job_id__contains", req.JobId).
		Filter("exec_day__in", req.ExecDay).Filter("exec_times__in", req.ExecTimes).Filter("valid__in", req.Valid).
		Count()
	if err != nil {
		rsp.Error = err.Error()
		goto Finish
	}

	_, err = o.QueryTable("tbl_job_ctl").Filter("job_id__contains", req.JobId).
		Filter("exec_day__in", req.ExecDay).Filter("exec_times__in", req.ExecTimes).Filter("valid__in", req.Valid).
		Limit(req.Length).Offset(req.Start).All(&rsp.Data)
	if err != nil && err != orm.ErrNoRows {
		rsp.Error = err.Error()
		goto Finish
	}

	rsp.Draw = req.Draw
	rsp.RecordsFiltered = rsp.RecordsTotal

	if len(rsp.Data) == 0 {
		rsp.Data = make([]*TblJobCtl, 0)
	}

Finish:
	c.Data["json"] = rsp
	c.ServeJSON()
}

func (c *JobCtlController) Post() {
	req := new(TblJobCtl)
	rsp := &CronRsp{ErrorCode: "000", ErrorDesc: "success"}

	o := orm.NewOrm()

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil {
		beego.Error(err, "->", string(c.Ctx.Input.RequestBody))
		rsp.ErrorCode = "001"
		rsp.ErrorDesc = err.Error()
		goto Finish
	}

	if _, err := o.Insert(req); err != nil {
		rsp.ErrorCode = "002"
		rsp.ErrorDesc = err.Error()
		goto Finish
	}

	o.Commit()

Finish:
	c.Data["json"] = rsp
	c.ServeJSON()
}

func (c *JobCtlController) Put() {
	req := new(TblJobCtl)
	rsp := &CronRsp{ErrorCode: "000", ErrorDesc: "success"}

	o := orm.NewOrm()

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil {
		beego.Error(err, "->", string(c.Ctx.Input.RequestBody))
		rsp.ErrorCode = "001"
		rsp.ErrorDesc = err.Error()
		goto Finish
	}

	if _, err := o.Update(req); err != nil {
		rsp.ErrorCode = "002"
		rsp.ErrorDesc = err.Error()
		goto Finish
	}

	if _, err := o.QueryTable("tbl_job_dtl").
		Filter("job_id", req.JobId).Filter("job_status__in", []int{1, 2, 9}).Update(orm.Params{
		"jobName":       req.JobName,
		"command":       req.Command,
		"exec_day":      req.ExecDay,
		"exec_times":    req.ExecTimes,
		"timeout":       req.Timeout,
		"max_failures":  req.MaxFailures,
		"depend_job_id": req.DependJobId,
		"depend_custom": req.DependCustom,
		"update_time":   time.Now(),
	}); err != nil {
		rsp.ErrorCode = "002"
		rsp.ErrorDesc = err.Error()
		o.Rollback()
		goto Finish
	}

	o.Commit()

Finish:
	c.Data["json"] = rsp
	c.ServeJSON()
}

func (c *JobCtlController) Delete() {
	req := new(TblJobCtl)
	rsp := &CronRsp{ErrorCode: "000", ErrorDesc: "success"}

	_ = c.ParseForm(req)

	o := orm.NewOrm()

	if _, err := o.Delete(req); err != nil {
		rsp.ErrorCode = "002"
		rsp.ErrorDesc = err.Error()
		goto Finish
	}

	o.Commit()

Finish:
	c.Data["json"] = rsp
	c.ServeJSON()
}
